﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using API;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Core.Interceptors;
using libmp;
using mb;
using Xamarin.Essentials;

namespace libmp
{
    public class gRPC // : Interceptor
    {
        static mb.ILog logger = App.logger;
        public static gRPC Instance { get; set; }

        public Mb.UserService.UserServiceClient ServiceClient { get; set; }

        public static async void Init()
        {
            try
            {
                int gRpcPortOffset = 5; //应与服务器保持一致
                var rpcServerUrl = new Regex(":(.+$)").Replace(App.CurrentServerUrl, (m) => ":" + (int.Parse(m.Groups[1].Value) + gRpcPortOffset));
                var channelCredentials = new SslCredentials(File.ReadAllText(App.HotStorageRoot + "/ca.pem"));
                var channel = new Grpc.Core.Channel(rpcServerUrl, Grpc.Core.ChannelCredentials.Insecure);

                var options = new List<ChannelOption>();
                options.Add(new ChannelOption("grpc.ssl_target_name_override", "10.1.1.206"));
                options.Add(new ChannelOption("grpc.default_authority", "10.1.1.206"));
                channel = new Grpc.Core.Channel(rpcServerUrl, channelCredentials, options);
                var invoker = channel.Intercept(new mb.DeadlineInterceptor(5));
                var client = new Mb.UserService.UserServiceClient(invoker);
                // client = new Mb.UserService.UserServiceClient(channel);

                Instance = new gRPC() { ServiceClient = client };

                logger.Log("grpc connecting ---->>", rpcServerUrl);
                await channel.ConnectAsync(DateTime.UtcNow.AddSeconds(5));
                logger.Log("grpc connected  <<----");
            }
            catch (System.Exception e)
            {
                logger.Log("grpc error", e);
            }
        }
    }
}